package kn.xianSubway.report;

import com.alibaba.excel.EasyExcel;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 类描述：执行
 *
 * @author XJW
 * @since 2025/6/12 11:43
 */
public class ExportESDataToExcel {
    private static final String INDEX_NAME = "monitordomesticdatal2";
    private static final String USERNAME = "elastic";
    private static final String PASSWORD = "konne20211220@.+";
    private static final String HOST = "10.1.96.34";
    private static final int PORT = 9200;

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = createClient();

        final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(2L));
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 设置 term 查询条件 monitorId = 24632
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("monitorId", 24632))
                .filter(QueryBuilders.rangeQuery("createTime")
                        .gte("2025-06-06T00:00:00+08:00")
                        .lt("2025-06-13T00:00:00+08:00")
                        .format("strict_date_time"));  // 指定时间格式为 ISO 8601

        sourceBuilder.query(boolQuery);
        sourceBuilder.size(1000);
        sourceBuilder.sort("_doc", SortOrder.ASC);


        // 指定返回字段
        sourceBuilder.fetchSource(
                new String[]{"content", "author", "website", "title", "releaseTime", "keyword", "source"},
                null
        );

        searchRequest.source(sourceBuilder);
        searchRequest.scroll(scroll);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        String scrollId = searchResponse.getScrollId();
        SearchHit[] searchHits = searchResponse.getHits().getHits();

        List<ESData> totalList = new ArrayList<>();

        while (searchHits != null && searchHits.length > 0) {
            for (SearchHit hit : searchHits) {
                Map<String, Object> source = hit.getSourceAsMap();
                ESData data = new ESData();

                data.setContent(truncate((String) source.getOrDefault("content", "")));
                data.setAuthor(truncate((String) source.getOrDefault("author", "")));
                data.setWebsite(truncate((String) source.getOrDefault("website", "")));
                data.setTitle(truncate((String) source.getOrDefault("title", "")));
                data.setReleaseTime(truncate((String) source.getOrDefault("releaseTime", "")));
                data.setKeyword(truncate((String) source.getOrDefault("keyword", "")));
                data.setSource(truncate((String) source.getOrDefault("source", "")));

                totalList.add(data);
            }

            // 下一页
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            scrollRequest.scroll(scroll);
            searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
            scrollId = searchResponse.getScrollId();
            searchHits = searchResponse.getHits().getHits();
        }

        // 写入 Excel 文件
        String fileName = "es_export_" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(new File(fileName), ESData.class).sheet("ES数据导出").doWrite(totalList);

        System.out.println("导出完成，文件路径：" + new File(fileName).getAbsolutePath());

        // 清理 Scroll
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollId);
        client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        client.close();
    }

    private static RestHighLevelClient createClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(USERNAME, PASSWORD));

        RestClientBuilder builder = RestClient.builder(new HttpHost(HOST, PORT, "http"))
                .setHttpClientConfigCallback(httpClientBuilder ->
                        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                );

        return new RestHighLevelClient(builder);
    }
    private static String truncate(String text) {
        if (text == null) return "";
        return text.length() > 32767 ? text.substring(0, 32767) : text;
    }

}
